package com.suvel.study.service.impl;

import com.suvel.study.dao.CodeDao;
import com.suvel.study.pojo.LagouAuthCode;
import com.suvel.study.service.CodeService;
import com.suvel.study.service.EmailService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;

import org.springframework.util.StringUtils;

import java.util.Date;

@RefreshScope
@Service
public class CodeServiceImpl implements CodeService {

    @Value("${expiration}")
    private Long expiration;
    @Autowired
    private CodeDao codeDao;
    @Reference(timeout = 2000)
    private EmailService emailService;
    @Override
    public Integer validate(String email, String code) {
        int status = 1;
        if (!StringUtils.isEmpty(email) && !StringUtils.isEmpty(code)) {
            LagouAuthCode lagouAuthCode = codeDao.findLastCodeByEmail(email);
            if (lagouAuthCode != null) {
                String savedCode = lagouAuthCode.getCode();
                Date now = new Date();
                // 验证码超时
                if (savedCode.equals(code)) {
                    // 验证码匹配，正确
                    if (now.compareTo(lagouAuthCode.getExpiretime()) < 0) {
                        status = 0;
                    } else {
                        status = 2;
                    }
                }
            }
        }
        return status;
    }

    @Override
    public LagouAuthCode saveByEmail(String email) {
        if (StringUtils.isEmpty(email)) {
            throw new RuntimeException("邮箱为空，生成验证码失败！");
        }
        Date now = new Date();
        Date expireTime = new Date(now.getTime() + expiration);
        Integer codeInt = (int) ((Math.random() * 9 + 1) * 100000);
        String code = String.valueOf(codeInt);
        LagouAuthCode saveLagouAuthCodeEntity = new LagouAuthCode();
        saveLagouAuthCodeEntity.setCode(code);
        saveLagouAuthCodeEntity.setEmail(email);
        saveLagouAuthCodeEntity.setCreatetime(now);
        saveLagouAuthCodeEntity.setExpiretime(expireTime);
        return codeDao.save(saveLagouAuthCodeEntity);
    }

    @Override
    public void createAndSend(String email) {
        LagouAuthCode lagouAuthCodeEntity = saveByEmail(email);
        if (StringUtils.isEmpty(lagouAuthCodeEntity.getCode())) {
            throw new RuntimeException("生成验证码失败！");
        } else {
            String code = lagouAuthCodeEntity.getCode();
            //发送邮件
            Boolean result = emailService.sendEmailCode(email, code);
            if (result == null || !result){
                throw new RuntimeException("发送验证邮件失败！");
            }
        }
    }
}
